package com.lsh.radardemo;

import android.graphics.PointF;
import android.os.*;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import java.io.*;
import java.lang.Process;
import java.util.*;
import java.util.regex.*;

public class RadarDisplayActivity extends AppCompatActivity {
    private TextView tvPoint, tvAngle, tvDistance;
    private RadarView radarView;
    private final Handler handler = new Handler(Looper.getMainLooper());
    private Process radarProcess;
    private final List<PointF> radarPoints = new ArrayList<>();
    private static final int MAX_POINTS = 720;
    private long lastUpdateTime = 0;
    private static final int UPDATE_INTERVAL_MS = 33;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radar_display);

        tvPoint = findViewById(R.id.tvPoint);
        tvAngle = findViewById(R.id.tvAngle);
        tvDistance = findViewById(R.id.tvDistance);
        radarView = findViewById(R.id.radarView);

        // 添加返回主界面按钮点击事件
        android.widget.Button btnBack = findViewById(R.id.btnBack);
        btnBack.setOnClickListener(v -> finish());

        startRadarProcess();
    }

    private void startRadarProcess() {
        new Thread(() -> {
            try {
                radarProcess = Runtime.getRuntime().exec(new String[]{
                        "sh", "-c", "export LD_LIBRARY_PATH=/data/local/tmp && /data/local/tmp/nvilidar_test"
                });

                BufferedReader reader = new BufferedReader(new InputStreamReader(radarProcess.getInputStream()));
                Pattern pattern = Pattern.compile("points\\[(\\d+)]\\s*:\\s*angle=([-\\d\\.]+).*?distance=([\\d\\.]+)m");

                String line;
                while ((line = reader.readLine()) != null) {
                    Log.d("radar-line", line);
                    Matcher matcher = pattern.matcher(line);
                    if (matcher.find()) {
                        int index = Integer.parseInt(matcher.group(1));
                        double angleDeg = Double.parseDouble(matcher.group(2));
                        double distanceM = Double.parseDouble(matcher.group(3));

                        if (distanceM <= 0 || index >= MAX_POINTS) continue;

                        float x = (float) (distanceM * Math.cos(Math.toRadians(angleDeg)));
                        float y = (float) (distanceM * Math.sin(Math.toRadians(angleDeg)));

                        synchronized (radarPoints) {
                            while (radarPoints.size() <= index) {
                                radarPoints.add(new PointF(0, 0));
                            }
                            radarPoints.set(index, new PointF(x, y));
                        }

                        long now = System.currentTimeMillis();
                        if (now - lastUpdateTime >= UPDATE_INTERVAL_MS) {
                            lastUpdateTime = now;
                            List<PointF> copy;
                            synchronized (radarPoints) {
                                copy = new ArrayList<>(radarPoints);
                            }
                            handler.post(() -> {
                                radarView.setPoints(copy);
                                tvPoint.setText("Point: " + index);
                                tvAngle.setText("Angle: " + angleDeg + "°");
                                tvDistance.setText("Distance: " + distanceM + "m");
                            });
                        }
                    }
                }

            } catch (IOException e) {
                handler.post(() -> tvPoint.setText("执行失败: " + e.getMessage()));
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (radarProcess != null) radarProcess.destroy();
    }
}
